package com.universest.swordholder.ui.screen
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.ArrowDropUp
import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.universest.swordholder.R
import com.universest.swordholder.SwordHolderApplication
import com.universest.swordholder.ui.theme.SwordHolderTheme
import com.universest.swordholder.viewmodel.WorksViewModel
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.TextButton
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewModelScope
import com.universest.swordholder.data.dao.Book
import com.universest.swordholder.ui.activity.BaseActivity
import com.universest.swordholder.ui.activity.PassageEditActivity
import com.universest.swordholder.ui.item.WorksItemWidget
import com.universest.swordholder.ui.widget.CardDialog
import com.universest.swordholder.ui.widget.EnsureDialog
import com.universest.swordholder.ui.widget.ProgressMode
import com.universest.swordholder.ui.widget.TaskProgressWidget
import kotlinx.coroutines.launch


@Composable
fun WorksScreen(modifier: Modifier = Modifier,viewModel: WorksViewModel = viewModel()) {
    val context = LocalContext.current
    val filterType by viewModel.filterWorksType.collectAsStateWithLifecycle()
    var newWorksDialogVisible by remember { mutableStateOf(false) }
    // 添加文件选择启动器
    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            // 处理选中的文件
            viewModel.viewModelScope.launch {
                val result = viewModel.handleTxtFileImport(it)
                if(result.isSuccess){
                    (context as? BaseActivity)?.toast(context.getString(R.string.import_success))
                }else{
                    (context as? BaseActivity)?.toast(context.getString(R.string.import_failed))
                }
            }
        }
    }
    Column(modifier = modifier) {
        Row(modifier = Modifier
            .fillMaxWidth()
            .height(60.dp),verticalAlignment = Alignment.CenterVertically) {
            var filterMenuExpanded by remember { mutableStateOf(false) }
            var moreMenuExpanded by remember { mutableStateOf(false) }
            Row (modifier = Modifier
                .padding(start = 20.dp)
                .clickable(onClick = { filterMenuExpanded = !filterMenuExpanded })
                .wrapContentWidth(), verticalAlignment = Alignment.CenterVertically){
                Text(text = when(filterType){
                    WorksViewModel.WorksType.ALL -> context.getString(R.string.works)
                    WorksViewModel.WorksType.BOOK -> context.getString(R.string.books)
                    WorksViewModel.WorksType.SINGLE_PASSAGE -> context.getString(R.string.single_passage)
                }, color = MaterialTheme.colorScheme.onSurface, fontSize = 23.sp)
                Icon(
                        imageVector = if(filterMenuExpanded)Icons.Filled.ArrowDropDown else Icons.Filled.ArrowDropUp,
                        contentDescription = null
                )
                DropdownMenu(
                    expanded = filterMenuExpanded,
                    onDismissRequest = {
                        filterMenuExpanded = false
                    }
                ) {
                    val workTypes = listOf(
                        WorksViewModel.WorksType.ALL to R.string.all,
                        WorksViewModel.WorksType.BOOK to R.string.books,
                        WorksViewModel.WorksType.SINGLE_PASSAGE to R.string.single_passage
                    )

                    workTypes.forEach { (type, labelRes) ->
                        DropdownMenuItem(
                            text = {
                                Row {
                                    val fontSize = 19.sp
                                    Text(fontSize = fontSize, text = context.getString(labelRes))
                                    if (filterType == type) {
                                        Text(
                                            fontSize = fontSize,
                                            modifier = Modifier.padding(start = 30.dp),
                                            text = context.getString(R.string.tick)
                                        )
                                    }
                                }
                            },
                            onClick = {
                                viewModel.setFilterWorksType(type)
                                filterMenuExpanded = false
                            }
                        )
                    }

                }
            }
            Box(modifier = Modifier.weight(1f))
            Row(modifier = Modifier) {
                IconButton(onClick = {}) {
                    Icon(imageVector = Icons.Default.Search, contentDescription = null)
                }
                IconButton(onClick = {
                    moreMenuExpanded = true
                }) {
                    Icon(imageVector = Icons.Default.MoreHoriz, contentDescription = null)
                }
                DropdownMenu(expanded = moreMenuExpanded, onDismissRequest = { moreMenuExpanded = false }) {
                    DropdownMenuItem(text = { Text(text = context.getString(R.string.add_works)) }
                        , onClick = {
                            newWorksDialogVisible = true
                            moreMenuExpanded = false
                        })
                    DropdownMenuItem(text = { Text(text = context.getString(R.string.import_txt)) }
                        , onClick = {
                            filePickerLauncher.launch("text/plain")
                            moreMenuExpanded = false
                        })
                }
            }
        }
        Box(modifier = Modifier
            .fillMaxWidth()
            .weight(1f)){
            val books by viewModel.books.collectAsStateWithLifecycle(null)
            if(books == null){
                // 添加居中的 Loading 动画
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .wrapContentSize(Alignment.Center)
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(48.dp),
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }else if(books?.isEmpty() == true){
                Text(text = context.getString(when(filterType){
                    WorksViewModel.WorksType.ALL -> R.string.no_works
                    WorksViewModel.WorksType.BOOK -> R.string.no_works_for_filter_books
                    WorksViewModel.WorksType.SINGLE_PASSAGE -> R.string.no_works_for_filter_single_passage
                }),
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.align(Alignment.Center))
            }else{
                LazyColumn {
                    items(books?:emptyList<Book>()) { book ->
                        val description by viewModel.getBookDescription(book).collectAsStateWithLifecycle()
                        var showDropMenu by remember { mutableStateOf(false) }
                        var ensureDeleteBookDialog by remember { mutableStateOf(false) }
                        if(ensureDeleteBookDialog){
                            EnsureDialog(text = context.getString(
                                R.string.ensure_remove_works,
                                book.bookName
                            ), onEnsureOrCancel = {
                                if(it){
                                    viewModel.removeBook(book.bookId)
                                }
                                ensureDeleteBookDialog = false
                            })
                        }
                        var showModifyWorksDialog by remember { mutableStateOf(false) }
                        if(showModifyWorksDialog) {
                            ModifyWorksDialog(
                                book = book,
                                onDismissRequest = { showModifyWorksDialog = false },
                                viewModel = viewModel
                            )
                        }
                        WorksItemWidget(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(100.dp)
                                .combinedClickable(onLongClick = {
                                    showDropMenu = true
                                }, onClick = {
                                    val intent = Intent(context, PassageEditActivity::class.java)
                                    intent.putExtra("bookId", book.bookId)
                                    context.startActivity(intent)
                                })
                                .padding(start = 15.dp, end = 15.dp, top = 10.dp, bottom = 10.dp),
                            description =  description,
                            book = book, dropMenu = {
                                DropdownMenu(
                                    expanded = showDropMenu,
                                    onDismissRequest = {
                                        showDropMenu = false
                                    }
                                ) {
                                    DropdownMenuItem(text = { Text(text = stringResource(R.string.modify_this_book_info)) }
                                        , onClick = {
                                            showModifyWorksDialog = true
                                            showDropMenu = false
                                        })
                                    DropdownMenuItem(text = { Text(text = stringResource(R.string.delete_this_book)) }
                                        , onClick = {
                                            ensureDeleteBookDialog = true
                                            showDropMenu = false
                                        })
                                }
                            })

                    }
                }
            }
        }
        if(newWorksDialogVisible){
            NewWorksDialog(viewModel = viewModel, onDismissRequest = {
                newWorksDialogVisible = false
            })
        }
    }
    TaskDialog(viewModel = viewModel)
}

@Composable
fun TaskDialog(viewModel: WorksViewModel){
    if(viewModel.tasks.isEmpty())return
    CardDialog(onDismissRequest = {}) {
        Column {
            viewModel.tasks.forEach { task->
                TaskProgressWidget(task = task, progressMode = ProgressMode.Percentage)
            }
        }
    }
}

@Composable
fun ModifyWorksDialog(modifier: Modifier = Modifier,book:Book, onDismissRequest: () -> Unit = {}, viewModel: WorksViewModel) {
    val context = LocalContext.current
    var title by remember(book.bookName) { mutableStateOf(book.bookName) }
    var description by remember(book.bookDescription) { mutableStateOf(book.bookDescription) }
    var showTitleEmptyError by remember { mutableStateOf(false) } // 添加错误状态

    CardDialog(onDismissRequest = onDismissRequest) {
        Column(modifier = Modifier.padding(20.dp)) {
            Text(
                text = stringResource(R.string.modify_this_book_info),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            OutlinedTextField(
                value = title,
                onValueChange = {
                    title = it
                    if (showTitleEmptyError && it.isNotEmpty()) {
                        showTitleEmptyError = false
                    }
                },
                label = { Text(text = context.getString(R.string.work_title)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                singleLine = true,
                isError = showTitleEmptyError
            )

            // 显示错误信息
            if (showTitleEmptyError) {
                Text(
                    text = context.getString(R.string.title_required),
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodySmall,
                    modifier = Modifier.padding(start = 16.dp)
                )
            }

            OutlinedTextField(
                value = description,
                onValueChange = { description = it },
                label = { Text(text = context.getString(R.string.work_description)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(120.dp),
                singleLine = false
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.End
            ) {
                TextButton(
                    onClick = onDismissRequest,
                    modifier = Modifier.padding(end = 8.dp)
                ) {
                    Text(text = context.getString(R.string.cancel))
                }
                Button(
                    onClick = {
                        if(title.isEmpty()){
                            showTitleEmptyError = true // 显示错误提示
                            return@Button
                        }
                        viewModel.updateBook(book.copy(bookName = title, bookDescription = description))
                        onDismissRequest()
                    }
                ) {
                    Text(text = "更新")
                }
            }
        }
    }
}

@Composable
fun NewWorksDialog(modifier: Modifier = Modifier, onDismissRequest: () -> Unit = {}, viewModel: WorksViewModel) {
    val context = LocalContext.current
    var title by remember { mutableStateOf("") }
    var isSinglePassage by remember { mutableStateOf(false) }
    var description by remember { mutableStateOf("") }
    var showTitleEmptyError by remember { mutableStateOf(false) } // 添加错误状态

    CardDialog(onDismissRequest = onDismissRequest) {
        Column(modifier = Modifier.padding(20.dp)) {
            Text(
                text = context.getString(R.string.create_new_work),
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            OutlinedTextField(
                value = title,
                onValueChange = {
                    title = it
                    if (showTitleEmptyError && it.isNotEmpty()) {
                        showTitleEmptyError = false // 当用户开始输入时清除错误提示
                    }
                },
                label = { Text(text = context.getString(R.string.work_title)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                singleLine = true,
                isError = showTitleEmptyError // 标题为空时显示错误状态
            )

            // 显示错误信息
            if (showTitleEmptyError) {
                Text(
                    text = context.getString(R.string.title_required),
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodySmall,
                    modifier = Modifier.padding(start = 16.dp)
                )
            }

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = isSinglePassage,
                    onCheckedChange = { isSinglePassage = it }
                )
                Text(
                    modifier = Modifier.clickable(onClick = { isSinglePassage = !isSinglePassage }),
                    text = context.getString(R.string.is_single_passage))
            }

            OutlinedTextField(
                value = description,
                onValueChange = { description = it },
                label = { Text(text = context.getString(R.string.work_description)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(120.dp),
                singleLine = false
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.End
            ) {
                TextButton(
                    onClick = onDismissRequest,
                    modifier = Modifier.padding(end = 8.dp)
                ) {
                    Text(text = context.getString(R.string.cancel))
                }
                Button(
                    onClick = {
                        if(title.isEmpty()){
                            showTitleEmptyError = true // 显示错误提示
                            return@Button
                        }
                        viewModel.createNewBook(title,description,isSinglePassage)
                        onDismissRequest()
                    }
                ) {
                    Text(text = context.getString(R.string.create))
                }
            }
        }
    }
}


@Composable
@Preview
fun WorksScreenPreview() {
    SwordHolderApplication.previewContext = LocalContext.current
    SwordHolderTheme {
        WorksScreen(modifier = Modifier
            .fillMaxWidth()
            .height(600.dp))
    }
}